﻿using Manon.Autofac;
using Manon.Core.Commons;
using Manon.Gateway.ApplicationCore.Dtos.GlobalConfiguration;
using Manon.Gateway.ApplicationCore.Entities;
using Manon.Gateway.ApplicationCore.Infrastructure;
using Manon.Gateway.ApplicationCore.Interfaces;
using Manon.Repository;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Manon.Gateway.ApplicationCore.Services
{
    public class GlobalConfigurationService : IGlobalConfigurationService, ISingletonDependency
    {

        /// <summary>
        /// 保存全局设置
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<Result> SaveGlobalConfiguration(SaveGlobalConfigurationInput Input)
        {
            var logger = Resolver.Resolve<ILogger<RouteService>>();
            try
            {
                var unitOfWork = Resolver.Resolve<IUnitOfWork<GatewayDbContext>>();

                var repos = unitOfWork.GetRepository<GlobalConfiguration>();
                var result = await repos.GetFirstOrDefaultAsync(n => n.Id == Input.Id);
                if (result == null)
                {
                    result = Input.ConvertTo<SaveGlobalConfigurationInput, GlobalConfiguration>();
                    await repos.InsertAsync(result);
                }
                else
                {

                    var newRoutes = Input.ConvertTo<SaveGlobalConfigurationInput, GlobalConfiguration>();
                    repos.Update(newRoutes);
                }
                await unitOfWork.SaveChangesAsync();
                return Result.Successed("保存成功!");

            }
            catch (Exception ex)
            {
                logger.LogError("保存全局设置异常", ex);
                throw;
            }
        }
        /// <summary>
        /// 获取全局设置
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<GetGlobalConfigurationOutput> GetGlobalConfiguration()
        {
            var logger = Resolver.Resolve<ILogger<RouteService>>();
            try
            {
                var unitOfWork = Resolver.Resolve<IUnitOfWork<GatewayDbContext>>();

                var repos = unitOfWork.GetRepository<GlobalConfiguration>();

                return await repos.GetFirstOrDefaultAsync<GetGlobalConfigurationOutput>();
            }
            catch (Exception ex)
            {
                logger.LogError("获取全局设置异常", ex);
                throw;
            }
        }

    }
}
